/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.suli.check.rest;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.suli.check.domain.Checks;
import me.zhengjie.suli.check.service.ChecksService;
import me.zhengjie.suli.check.service.dto.ChecksQueryCriteria;
import me.zhengjie.suli.inventory.domain.Inventory;
import me.zhengjie.suli.inventory.repository.InventoryRepository;
import me.zhengjie.suli.location.domain.Location;
import me.zhengjie.suli.location.repository.LocationRepository;
import me.zhengjie.utils.ExcelUtils;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Allen Gao
 * @website https://eladmin.vip
 * @date 2023-02-09
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "盘点计划管理")
@RequestMapping("/api/checks")
@Slf4j
public class ChecksController {

    private final ChecksService checksService;
    private final InventoryRepository inventoryRepository;
    private final LocationRepository locationRepository;


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('checks:list')")
    public void exportChecks(HttpServletResponse response, ChecksQueryCriteria criteria) throws IOException {
        checksService.download(checksService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询盘点计划")
    @ApiOperation("查询盘点计划")
    @PreAuthorize("@el.check('checks:list')")
    public ResponseEntity<Object> queryChecks(ChecksQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(checksService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增盘点计划")
    @ApiOperation("新增盘点计划")
    @PreAuthorize("@el.check('checks:add')")
    public ResponseEntity<Object> createChecks(@Validated @RequestBody Checks resources) {
        return new ResponseEntity<>(checksService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改盘点计划")
    @ApiOperation("修改盘点计划")
    @PreAuthorize("@el.check('checks:edit')")
    public ResponseEntity<Object> updateChecks(@Validated @RequestBody Checks resources) {
        checksService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除盘点计划")
    @ApiOperation("删除盘点计划")
    @PreAuthorize("@el.check('checks:del')")
    public ResponseEntity<Object> deleteChecks(@RequestBody String[] ids) {
        checksService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping(value = "/generateCheckTasks")
    @Log("生成盘点任务")
    @ApiOperation("生成盘点任务")
    public ResponseEntity<Object> generateCheckTasks(@RequestBody String param) {
        return new ResponseEntity<>(checksService.generateCheckTasks(param), HttpStatus.CREATED);
    }

    @PostMapping(value = "/pdaGetOneCheckTaskByTrayName")
    @Log("PDA根据托盘名称查找盘点任务")
    @ApiOperation("PDA根据托盘名称查找盘点任务")
    public ResponseEntity<Object> pdaGetOneCheckTaskByTrayName(@RequestBody String trayName) {
        return new ResponseEntity<>(checksService.pdaGetOneCheckTaskByTrayName(trayName), HttpStatus.OK);
    }

    @PostMapping("/addCheckByLotCode")
    @ApiOperation("新增盘点任务")
    public ResponseEntity<Object> addCheckByMaterialCode(@RequestBody String param){
        return new ResponseEntity<>(checksService.addCheckByLotCode(param),HttpStatus.OK);
    }

    @PostMapping("/doCheck")
    @ApiOperation("执行盘点任务")
    public ResponseEntity<Object> doCheck(@RequestBody String param){
        return new ResponseEntity<>(checksService.doCheck(param),HttpStatus.OK);
    }

    @AnonymousPostMapping("/updateQty")
    @ApiOperation("盘差改数量")
    public ResponseEntity<Object> updateQTY(@RequestBody String param){
        return new ResponseEntity<>(checksService.updateQTY(param),HttpStatus.OK);
    }

    @PostMapping("/excel")
    @ApiOperation("接受excel文件")
    public ResponseEntity<Object> excel(@RequestParam("file") MultipartFile param) throws IOException {
        InputStream inputStream = param.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> read = reader.read();
        List<Inventory> inventoryList = new ArrayList<>();
        Snowflake snowflake = new Snowflake();
        for (List<Object> objects : read) {
            if (objects.get(0).equals("物料编号")){
                continue;
            }
            Inventory inventorys = inventoryRepository.findByBoxNumber(objects.get(3) + "");
            if (null != inventorys){
                continue;
            }
            Inventory inventory = new Inventory();
            inventory.setId(snowflake.nextIdStr());
            inventory.setMaterialCode(objects.get(0) + "");
            inventory.setMaterialName(objects.get(1) + "");
            inventory.setTotal(new BigDecimal(Integer.valueOf(objects.get(2) + "")));
            inventory.setAvailableQuantity(new BigDecimal(Integer.valueOf(objects.get(2) + "")));
            inventory.setGrade("");
            inventory.setIsHold(1);
            inventory.setHoldQuantity(new BigDecimal(0));
            inventory.setCreateTime(new Timestamp(new Date().getTime()));
            inventory.setTrayCode("");
            inventory.setVmiCode(objects.get(10) + "");
            inventory.setWarehouseLocation("暂存区");
            inventory.setLocationCode("暂存区");
            inventory.setElUnit(objects.get(3) + "");
            inventory.setLotCode(objects.get(4) + "");
            inventory.setBoxNumber(objects.get(5) + "");
            inventory.setZoneCode(objects.get(6) + "");
            inventory.setElMkDate(objects.get(7) + "");
            if (objects.size() > 8){
                inventory.setSuNo(null != objects.get(8)?objects.get(8) + "":""  );
                inventory.setSuName(null != objects.get(9)?objects.get(9) + "":"");
            }else{
                inventory.setSuNo("");
                inventory.setSuName("");
            }

//            inventory.setElMkDate(objects.get(11) + "");
            inventory.setStartDate(new Timestamp(new Date().getTime()));
            inventory.setCreateBy(SecurityUtils.getCurrentUsername());
            inventoryList.add(inventory);
        }
        reader.close();
        System.out.println(inventoryList);
        return new ResponseEntity<>("success",HttpStatus.OK);
    }

    @AnonymousPostMapping("/updateLocation")
    @ApiOperation("修改库位数据")
    public ResponseEntity<Object> updateLocation(){
        List<Location> locationByCw = locationRepository.getLocationByCw();
        log.info("变更前库位数据:" + locationByCw);
        List<Inventory> inventories = new ArrayList<>();
        List<Location> locations = new ArrayList<>();
        for (Location location : locationByCw) {
            String locationCode = location.getLocationCode();
            String[] split = locationCode.split("-");
            String head = split[0];
            String tui = split[2];
            String jiao = split[3].split("_")[0];
            String newLocationCode = head + "-006-" + tui + "-" + jiao +"_1";
            Inventory inventory = inventoryRepository.findByTrayCodeTop(location.getTrayCode());
            if (null != inventory){
                inventory.setLocationCode(newLocationCode);
                inventory.setWarehouseLocation(newLocationCode);
                inventories.add(inventory);
            }
            location.setLocationCode(newLocationCode);
            location.setWarehouseCode(newLocationCode);
            locations.add(location);
        }

        locationRepository.saveAll(locations);
        inventoryRepository.saveAll(inventories);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}